import { useEffect } from 'react';
import { EventEmitter } from 'events';
import { useMemoizedFn } from 'ahooks';

const eventBus = new EventEmitter();

const useEventBus = (eventName: string, handler: (...args: any[]) => void) => {
  const hanlderRef = useMemoizedFn(handler);

  useEffect(() => {
    eventBus.on(eventName, hanlderRef);

    return () => {
      eventBus.off(eventName, hanlderRef);
    };
  }, [eventName, hanlderRef]);
};

export { eventBus };

export default useEventBus;
